package com.example.work_cprovider2;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by asus on 2017/12/2.
 */

public class StuAdapter extends BaseAdapter{
    private Context context;
    private ArrayList<Student> stuData;
    private LocalBroadcastManager localBroadcastManager;
    private ContentResolver resolver;
    public StuAdapter(Context context,ArrayList<Student> stuData,LocalBroadcastManager localBroadcastManager,ContentResolver resolver){
        this.context = context;
        this.stuData = stuData;
        this.localBroadcastManager = localBroadcastManager;
        this.resolver = resolver;
    }
    @Override
    public int getCount() {
        return stuData.size();
    }

    @Override
    public Object getItem(int position) {
        return stuData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
            StuViewHolders holder = new StuViewHolders();
            holder.numbers = (TextView)convertView.findViewById(R.id.munber);
            holder.names = (TextView)convertView.findViewById(R.id.name);
            holder.ages = (TextView)convertView.findViewById(R.id.age);
            holder.deletes = (ImageView)convertView.findViewById(R.id.delte);
            convertView.setTag(holder);
        }
        final Student s = stuData.get(position);
        StuViewHolders holder = (StuViewHolders)convertView.getTag();
        holder.numbers.setText(String.valueOf(s.getMunber())+"号");
        holder.names.setText(s.getName());
        holder.ages.setText(String.valueOf(s.getAge())+"岁");
        holder.deletes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = s.getMunber();
                deleteData(id);
                Intent intent = new Intent("com.example.broadcast.ADD");
                 localBroadcastManager.sendBroadcast(intent);
            }
        });
        return convertView;
    }
    protected void deleteData(int id){
        Uri uri = Uri.parse("content://com.example.databasetext.provider/student");
        String ids = "munber = "+id;
        resolver.delete(uri,ids,null);
    }
    class StuViewHolders{
        TextView numbers;
        TextView names;
        TextView ages;
        ImageView deletes;
    }
}
